<template>
  <div class="form-designer">
    <div class="designer-sidebar">
      <div class="components-list">
        <div 
          v-for="group in formComponents" 
          :key="group.title" 
          class="component-group"
        >
          <div class="group-title">{{ group.title }}</div>
          <div class="group-content">
            <div 
              v-for="item in group.components" 
              :key="item.type"
              class="component-item"
              draggable="true"
              @dragstart="handleDragStart($event, item)"
            >
              <el-icon><component :is="item.icon" /></el-icon>
              <span>{{ item.label }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="designer-main">
      <div class="main-header">
        <div class="header-left">
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button label="design">设计</el-radio-button>
            <el-radio-button label="preview">预览</el-radio-button>
            <el-radio-button label="json">JSON</el-radio-button>
          </el-radio-group>
        </div>
        <div class="header-right">
          <el-button type="primary" link @click="handleCopy" v-if="viewMode === 'json'">
            <el-icon><CopyDocument /></el-icon>复制
          </el-button>
          <el-button type="primary" link @click="handleFormat" v-if="viewMode === 'json'">
            <el-icon><Operation /></el-icon>格式化
          </el-button>
        </div>
      </div>

      <!-- 设计模式 -->
      <div 
        v-show="viewMode === 'design'"
        class="form-canvas"
        @dragover.prevent
        @drop.prevent="handleDrop($event)"
      >
        <template v-if="formItems.length">
          <div 
            v-for="(item, index) in formItems" 
            :key="index"
            class="form-item"
            :class="{ active: currentEditingIndex === index }"
            @click.stop="handleItemClick(index)"
          >
            <!-- 子表单组件 -->
            <template v-if="item.type === 'table'">
              <div class="table-form">
                <div class="table-header">
                  <div class="table-title">
                    <el-icon><Grid /></el-icon>
                    <span>{{ item.label }}</span>
                  </div>
                </div>
                <div 
                  class="table-content"
                  @dragover.prevent
                  @drop.prevent="handleTableDrop($event, index)"
                >
                  <el-table :data="[{}]" border>
                    <el-table-column 
                      v-for="(col, colIndex) in item.columns" 
                      :key="colIndex"
                      :prop="col.name"
                      :label="col.label"
                      :width="col.width"
                    >
                      <template #header>
                        <div class="column-header">
                          <span>{{ col.label }}</span>
                          <el-button 
                            type="danger" 
                            link 
                            @click.stop="removeTableColumn(index, colIndex)"
                          >
                            <el-icon><Delete /></el-icon>
                          </el-button>
                        </div>
                      </template>
                      <template #default>
                        <component
                          :is="getColumnComponent(col.type)"
                          v-bind="col.props"
                          disabled
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                  <div v-if="!item.columns?.length" class="empty-tip">
                    <el-empty description="拖拽左侧组件到此处添加字段" />
                  </div>
                </div>
              </div>
            </template>
            
            <!-- 其他组件 -->
            <template v-else>
              <div class="item-content">
                <el-icon><component :is="item.icon" /></el-icon>
                <span>{{ item.label }}</span>
              </div>
              <div class="item-actions">
                <el-button type="danger" link @click.stop="handleDeleteItem(index)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
          </div>
        </template>
        <el-empty v-else description="拖拽左侧组件到此处进行表单设计" />
      </div>

      <!-- 预览模式 -->
      <div v-show="viewMode === 'preview'" class="form-preview">
        <el-form :model="previewForm" label-width="120px">
          <template v-for="(item, index) in formItems" :key="index">
            <!-- 栅格布局 -->
            <template v-if="item.type === 'grid'">
              <el-row :gutter="item.props.gutter" :justify="item.props.justify" :align="item.props.align">
                <el-col 
                  v-for="(col, colIndex) in item.columns" 
                  :key="colIndex"
                  :span="col.span"
                  :offset="col.offset"
                  :xs="col.xs"
                  :sm="col.sm"
                  :md="col.md"
                  :lg="col.lg"
                  :xl="col.xl"
                >
                  <template v-for="(subItem, subIndex) in col.list" :key="subIndex">
                    <el-form-item :label="subItem.label" :required="subItem.required">
                      <component 
                        :is="getPreviewComponent(subItem.type)"
                        v-model="previewForm[subItem.name]"
                        v-bind="subItem.props"
                      />
                    </el-form-item>
                  </template>
                </el-col>
              </el-row>
            </template>
            
            <!-- 分割线 -->
            <template v-else-if="item.type === 'divider'">
              <el-divider 
                :content-position="item.props.contentPosition"
                :border-style="item.props.borderStyle"
                :style="item.style"
              >
                {{ item.label }}
              </el-divider>
            </template>
            
            <!-- 卡片布局 -->
            <template v-else-if="item.type === 'card'">
              <el-card 
                :shadow="item.props.shadow"
                :style="item.style"
                :body-style="item.props.bodyStyle"
                :header-style="item.props.headerStyle"
              >
                <template #header>
                  <div>{{ item.props.title }}</div>
                </template>
                <template v-for="(subItem, subIndex) in item.list" :key="subIndex">
                  <el-form-item :label="subItem.label" :required="subItem.required">
                    <component 
                      :is="getPreviewComponent(subItem.type)"
                      v-model="previewForm[subItem.name]"
                      v-bind="subItem.props"
                    />
                  </el-form-item>
                </template>
              </el-card>
            </template>
            
            <!-- 基础组件 -->
            <template v-else>
              <el-form-item :label="item.label" :required="item.required">
                <!-- 文本输入 -->
                <template v-if="item.type === 'input'">
                  <el-input 
                    v-model="previewForm[item.name]"
                    v-bind="item.props"
                    :placeholder="item.placeholder"
                  />
                </template>
                
                <!-- 多行文本 -->
                <template v-else-if="item.type === 'textarea'">
                  <el-input 
                    type="textarea"
                    v-model="previewForm[item.name]"
                    v-bind="item.props"
                    :placeholder="item.placeholder"
                  />
                </template>
                
                <!-- 数字输入 -->
                <template v-else-if="item.type === 'number'">
                  <el-input-number 
                    v-model="previewForm[item.name]"
                    v-bind="item.props"
                    :min="item.min"
                    :max="item.max"
                    :step="item.step"
                  />
                </template>
                
                <!-- 选择器 -->
                <template v-else-if="item.type === 'select'">
                  <el-select 
                    v-model="previewForm[item.name]"
                    v-bind="item.props"
                    :placeholder="item.placeholder"
                  >
                    <el-option 
                      v-for="opt in item.options"
                      :key="opt.value"
                      :label="opt.label"
                      :value="opt.value"
                    />
                  </el-select>
                </template>
                
                <!-- 日期选择 -->
                <template v-else-if="item.type === 'date'">
                  <el-date-picker
                    v-model="previewForm[item.name]"
                    v-bind="item.props"
                    :placeholder="item.placeholder"
                  />
                </template>
                
                <!-- 时间选择 -->
                <template v-else-if="item.type === 'time'">
                  <el-time-picker
                    v-model="previewForm[item.name]"
                    v-bind="item.props"
                    :placeholder="item.placeholder"
                  />
                </template>
                
                <!-- 开关 -->
                <template v-else-if="item.type === 'switch'">
                  <el-switch
                    v-model="previewForm[item.name]"
                    v-bind="item.props"
                  />
                </template>
                
                <!-- 评分 -->
                <template v-else-if="item.type === 'rate'">
                  <el-rate
                    v-model="previewForm[item.name]"
                    v-bind="item.props"
                  />
                </template>
                
                <!-- 滑块 -->
                <template v-else-if="item.type === 'slider'">
                  <el-slider
                    v-model="previewForm[item.name]"
                    v-bind="item.props"
                  />
                </template>
                
                <!-- 图片上传 -->
                <template v-else-if="item.type === 'image'">
                  <el-upload
                    v-bind="item.props"
                    action="#"
                    :auto-upload="false"
                  >
                    <el-button type="primary">点击上传</el-button>
                  </el-upload>
                </template>
                
                <!-- 文件上传 -->
                <template v-else-if="item.type === 'file'">
                  <el-upload
                    v-bind="item.props"
                    action="#"
                    :auto-upload="false"
                  >
                    <el-button type="primary">点击上传</el-button>
                  </el-upload>
                </template>
              </el-form-item>
            </template>
          </template>
          
          <!-- 添加预览表单的操作按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handlePreviewSubmit">提交</el-button>
            <el-button @click="handlePreviewReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- JSON模式 -->
      <div v-show="viewMode === 'json'" class="form-json">
        <el-input
          v-model="jsonContent"
          type="textarea"
          :rows="20"
          :readonly="true"
          :spellcheck="false"
        />
      </div>
    </div>

    <div class="designer-panel" v-if="currentEditingIndex !== -1">
      <div class="panel-header">
        <span>{{ getPanelTitle }}</span>
        <el-button type="primary" link @click="currentEditingIndex = -1">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      <div class="panel-content">
        <!-- 子表单属性编辑 -->
        <template v-if="currentEditingItem.type === 'table'">
          <el-form :model="currentEditingItem" label-width="80px">
            <el-form-item label="表单名称">
              <el-input v-model="currentEditingItem.label" />
            </el-form-item>
            <el-form-item label="字段标识">
              <el-input v-model="currentEditingItem.name" />
            </el-form-item>
            
            <!-- 添加表格行列设置 -->
            <el-divider>表格设置</el-divider>
            <el-form-item label="默认行数">
              <el-input-number 
                v-model="currentEditingItem.props.defaultRows" 
                :min="1" 
                :max="10"
                @change="handleRowsChange"
              />
            </el-form-item>
            <el-form-item label="最大行数">
              <el-input-number 
                v-model="currentEditingItem.props.maxRows" 
                :min="1" 
                :max="100"
              />
            </el-form-item>
            <el-form-item label="表格样式">
              <el-checkbox v-model="currentEditingItem.props.border">显示边框</el-checkbox>
              <el-checkbox v-model="currentEditingItem.props.stripe">斑马纹</el-checkbox>
            </el-form-item>
            
            <el-divider>列配置</el-divider>
            <div class="columns-config">
              <div 
                v-for="(col, index) in currentEditingItem.columns" 
                :key="index"
                class="column-item"
              >
                <div class="column-header">
                  <span>列 {{ index + 1 }}</span>
                  <div class="column-actions">
                    <el-button 
                      type="primary" 
                      link 
                      @click="moveColumn(index, 'up')"
                      :disabled="index === 0"
                    >
                      <el-icon><ArrowUp /></el-icon>
                    </el-button>
                    <el-button 
                      type="primary" 
                      link 
                      @click="moveColumn(index, 'down')"
                      :disabled="index === currentEditingItem.columns.length - 1"
                    >
                      <el-icon><ArrowDown /></el-icon>
                    </el-button>
                    <el-button 
                      type="danger" 
                      link 
                      @click="removeColumn(index)"
                      :disabled="currentEditingItem.columns.length <= 1"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
                
                <el-form-item label="列名称">
                  <el-input v-model="col.label" />
                </el-form-item>
                <el-form-item label="列类型">
                  <el-select v-model="col.type" style="width: 100%">
                    <el-option label="单行文本" value="input" />
                    <el-option label="多行文本" value="textarea" />
                    <el-option label="数字" value="number" />
                    <el-option label="日期" value="date" />
                    <el-option label="选择器" value="select" />
                  </el-select>
                </el-form-item>
                <el-form-item label="列宽">
                  <el-input-number 
                    v-model="col.width" 
                    :min="50" 
                    :max="500"
                    :step="10"
                  />
                </el-form-item>
                <el-form-item label="必填">
                  <el-switch v-model="col.required" />
                </el-form-item>
                
                <!-- 根据列类型显示不同的属性配置 -->
                <template v-if="['input', 'textarea'].includes(col.type)">
                  <el-form-item label="占位文本">
                    <el-input v-model="col.props.placeholder" />
                  </el-form-item>
                  <el-form-item label="最大长度">
                    <el-input-number v-model="col.props.maxLength" :min="0" />
                  </el-form-item>
                </template>
                <template v-if="col.type === 'select'">
                  <el-form-item label="选项">
                    <div class="options-editor">
                      <div 
                        v-for="(opt, optIndex) in col.options" 
                        :key="optIndex"
                        class="option-item"
                      >
                        <el-input v-model="opt.label" placeholder="选项名称" />
                        <el-input v-model="opt.value" placeholder="选项值" />
                        <el-button type="danger" link @click="removeOption(col, optIndex)">
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </div>
                      <el-button type="primary" link @click="addOption(col)">
                        <el-icon><Plus /></el-icon>添加选项
                      </el-button>
                    </div>
                  </el-form-item>
                </template>
              </div>
              
              <el-button 
                type="primary" 
                plain 
                @click="addColumn"
                :disabled="currentEditingItem.columns.length >= 10"
              >
                <el-icon><Plus /></el-icon>添加列
              </el-button>
            </div>
          </el-form>
        </template>
        
        <!-- 其他组件的属性编辑保持不变 -->
        <template v-else>
          <el-form :model="currentEditingItem" label-width="80px">
            <el-form-item label="字段标识">
              <el-input v-model="currentEditingItem.name" placeholder="请输入字段标识" />
            </el-form-item>
            <el-form-item label="字段名称">
              <el-input v-model="currentEditingItem.label" placeholder="请输入字段名称" />
            </el-form-item>
            <el-form-item label="是否必填">
              <el-switch v-model="currentEditingItem.required" />
            </el-form-item>
            <el-form-item label="占位文本" v-if="['input', 'textarea'].includes(currentEditingItem.type)">
              <el-input v-model="currentEditingItem.placeholder" placeholder="请输入占位文本" />
            </el-form-item>
            <el-form-item label="最大长度" v-if="['input', 'textarea'].includes(currentEditingItem.type)">
              <el-input-number v-model="currentEditingItem.maxLength" :min="0" />
            </el-form-item>
            <el-form-item label="默认值">
              <el-input v-model="currentEditingItem.defaultValue" placeholder="请输入默认值" />
            </el-form-item>
            <el-form-item label="提示文本">
              <el-input v-model="currentEditingItem.tips" placeholder="请输入提示文本" />
            </el-form-item>
          </el-form>
        </template>
      </div>
    </div>

    <!-- 子表单设计对话框 -->
    <el-dialog
      v-model="showTableDialog"
      title="子表单设计"
      width="1000px"
      append-to-body
    >
      <div class="table-designer">
        <!-- 左侧组件列表 -->
        <div class="designer-sidebar">
          <div class="components-list">
            <div class="component-group">
              <div class="group-title">基础字段</div>
              <div class="group-content">
                <div 
                  v-for="item in basicComponents" 
                  :key="item.type"
                  class="component-item"
                  draggable="true"
                  @dragstart="handleDragStart($event, item)"
                >
                  <el-icon><component :is="item.icon" /></el-icon>
                  <span>{{ item.label }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 中间设计区域 -->
        <div class="table-main">
          <div class="table-columns">
            <div class="columns-header">
              <span>表单字段</span>
            </div>
            <div 
              class="columns-container"
              @dragover.prevent
              @drop.prevent="handleTableDrop"
            >
              <el-table :data="currentEditingItem.columns" border>
                <el-table-column type="index" width="50" label="#" />
                <el-table-column label="字段名称" min-width="120">
                  <template #default="{ row }">
                    <div 
                      class="column-cell"
                      :class="{ active: currentEditingColumn === row }"
                      @click="handleColumnClick(row)"
                    >
                      {{ row.label }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="字段类型" width="120">
                  <template #default="{ row }">
                    <el-tag>{{ row.label }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="必填" width="80" align="center">
                  <template #default="{ row }">
                    <el-switch v-model="row.required" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" align="center">
                  <template #default="{ $index }">
                    <el-button type="danger" link @click="removeTableColumn($index)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <!-- 右侧属性面板 -->
        <div class="table-panel" v-if="currentEditingColumn">
          <div class="panel-header">
            <span>字段属性</span>
            <el-button type="primary" link @click="currentEditingColumn = null">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
          <div class="panel-content">
            <el-form :model="currentEditingColumn" label-width="80px">
              <el-form-item label="字段名称">
                <el-input v-model="currentEditingColumn.label" placeholder="请输入字段名称" />
              </el-form-item>
              <el-form-item label="字段标识">
                <el-input v-model="currentEditingColumn.name" placeholder="请输入字段标识" />
              </el-form-item>
              <el-form-item label="是否必填">
                <el-switch v-model="currentEditingColumn.required" />
              </el-form-item>
              <el-form-item label="默认值">
                <el-input v-model="currentEditingColumn.defaultValue" placeholder="请输入默认值" />
              </el-form-item>
              <el-form-item label="提示文本">
                <el-input v-model="currentEditingColumn.tips" placeholder="请输入提示文本" />
              </el-form-item>
              <!-- 根据字段类型显示不同的属性配置 -->
              <template v-if="['input', 'textarea'].includes(currentEditingColumn.type)">
                <el-form-item label="占位文本">
                  <el-input v-model="currentEditingColumn.placeholder" placeholder="请输入占位文本" />
                </el-form-item>
                <el-form-item label="最大长度">
                  <el-input-number v-model="currentEditingColumn.maxLength" :min="0" />
                </el-form-item>
              </template>
              <template v-if="currentEditingColumn.type === 'number'">
                <el-form-item label="最小值">
                  <el-input-number v-model="currentEditingColumn.min" />
                </el-form-item>
                <el-form-item label="最大值">
                  <el-input-number v-model="currentEditingColumn.max" />
                </el-form-item>
                <el-form-item label="步长">
                  <el-input-number v-model="currentEditingColumn.step" :min="0" :precision="2" />
                </el-form-item>
              </template>
              <template v-if="['select', 'radio', 'checkbox'].includes(currentEditingColumn.type)">
                <el-form-item label="选项">
                  <div class="options-editor">
                    <div 
                      v-for="(opt, index) in currentEditingColumn.options" 
                      :key="index"
                      class="option-item"
                    >
                      <el-input v-model="opt.label" placeholder="选项名称" />
                      <el-input v-model="opt.value" placeholder="选项值" />
                      <el-button type="danger" link @click="removeOption(index)">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                    <el-button type="primary" link @click="addOption(currentEditingColumn)">
                      <el-icon><Plus /></el-icon>添加选项
                    </el-button>
                  </div>
                </el-form-item>
              </template>
            </el-form>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTableDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveTable">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { componentGroups } from '@/config/form-components'
import { ElMessage } from 'element-plus'
import { 
  Document, 
  Edit, 
  Delete, 
  Plus, 
  Switch,
  CopyDocument,
  Operation,
  Close,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['update:modelValue'])

// 使用导入的组件配置
const formComponents = componentGroups

// 表单项列表
const formItems = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 视图模式
const viewMode = ref('design')
const currentEditingIndex = ref(-1)
const currentEditingItem = ref({})

// 预览表单数据
const previewForm = ref({})

// 监听表单项变化，更新预览表单的默认值
watch(formItems, (items) => {
  const newForm = {}
  const processItems = (list) => {
    list.forEach(item => {
      if (item.type === 'grid') {
        item.columns.forEach(col => {
          if (col.list) {
            processItems(col.list)
          }
        })
      } else if (item.type === 'card') {
        if (item.list) {
          processItems(item.list)
        }
      } else if (item.name) {
        newForm[item.name] = item.defaultValue
      }
    })
  }
  processItems(items)
  previewForm.value = newForm
}, { deep: true })

// 预览表单的提交和重置
const handlePreviewSubmit = () => {
  ElMessage.success('提交成功')
  console.log('表单数据:', previewForm.value)
}

const handlePreviewReset = () => {
  const defaultForm = {}
  const processItems = (list) => {
    list.forEach(item => {
      if (item.type === 'grid') {
        item.columns.forEach(col => {
          if (col.list) {
            processItems(col.list)
          }
        })
      } else if (item.type === 'card') {
        if (item.list) {
          processItems(item.list)
        }
      } else if (item.name) {
        defaultForm[item.name] = item.defaultValue
      }
    })
  }
  processItems(formItems.value)
  previewForm.value = defaultForm
  ElMessage.success('重置成功')
}

// 处理拖拽开始
const handleDragStart = (event, item) => {
  event.dataTransfer.setData('componentData', JSON.stringify({
    ...item,
    name: `field_${Date.now()}`  // 生成唯一字段标识
  }))
}

// 处理拖拽放置
const handleDrop = (event, target) => {
  const data = event.dataTransfer.getData('componentData')
  if (data) {
    try {
      const componentData = JSON.parse(data)
      
      // 如果有目标位置，说明是拖入栅格列中
      if (target) {
        const { index, colIndex } = target
        if (!formItems.value[index].columns[colIndex].list) {
          formItems.value[index].columns[colIndex].list = []
        }
        formItems.value[index].columns[colIndex].list.push(componentData)
      } else {
        // 拖入顶层
        formItems.value.push(componentData)
      }
    } catch (error) {
      console.error('解析组件数据失败:', error)
    }
  }
}

// 处理组件点击
const handleItemClick = (index) => {
  currentEditingIndex.value = index
  currentEditingItem.value = { ...formItems.value[index] }
  
  // 如果是子表单，打开设计对话框
  if (formItems.value[index].type === 'table') {
    showTableDialog.value = true
    // 初始化预览数据
    previewData.value = [{}]
  }
}

// 处理删除组件
const handleDeleteItem = (index) => {
  formItems.value.splice(index, 1)
  if (currentEditingIndex.value === index) {
    currentEditingIndex.value = -1
  }
}

// 处理子项点击
const handleSubItemClick = (index, colIndex, subIndex) => {
  currentEditingIndex.value = `${index}-${colIndex}-${subIndex}`
  currentEditingItem.value = { 
    ...formItems.value[index].columns[colIndex].list[subIndex] 
  }
}

// 处理删除子项
const handleDeleteSubItem = (index, colIndex, subIndex) => {
  formItems.value[index].columns[colIndex].list.splice(subIndex, 1)
  if (currentEditingIndex.value === `${index}-${colIndex}-${subIndex}`) {
    currentEditingIndex.value = -1
  }
}

// 监听编辑项的变化，同步到表单项
watch(currentEditingItem, (newVal) => {
  if (currentEditingIndex.value !== -1) {
    if (typeof currentEditingIndex.value === 'string') {
      // 更新栅格内的组件
      const [index, colIndex, subIndex] = currentEditingIndex.value.split('-')
      formItems.value[index].columns[colIndex].list[subIndex] = { ...newVal }
    } else {
      // 更新顶层组件
      formItems.value[currentEditingIndex.value] = { ...newVal }
    }
  }
}, { deep: true })

// JSON内容
const jsonContent = computed(() => {
  const formData = {
    items: formItems.value.map(item => ({
      ...item,
      id: item.name,
      createTime: new Date().toISOString()
    }))
  }
  return JSON.stringify(formData, null, 2)
})

// 复制JSON
const handleCopy = async () => {
  try {
    await navigator.clipboard.writeText(jsonContent.value)
    ElMessage.success('复制成功')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 格式化JSON
const handleFormat = () => {
  try {
    const parsed = JSON.parse(jsonContent.value)
    jsonContent.value = JSON.stringify(parsed, null, 2)
    ElMessage.success('格式化成功')
  } catch (error) {
    ElMessage.error('JSON格式错误')
  }
}

// 获取预览组件
const getPreviewComponent = (type) => {
  const componentMap = {
    input: 'el-input',
    textarea: 'el-input',
    number: 'el-input-number',
    select: 'el-select',
    radio: 'el-radio-group',
    checkbox: 'el-checkbox-group',
    switch: 'el-switch',
    date: 'el-date-picker',
    time: 'el-time-picker'
  }
  return componentMap[type] || 'el-input'
}

// 添加栅格相关方
const currentColumnCount = computed({
  get: () => currentEditingItem.value?.columns?.length || 2,
  set: (val) => handleColumnCountChange(val)
})

const handleColumnCountChange = (count) => {
  const oldCount = currentEditingItem.value.columns.length
  const spans = currentEditingItem.value.columnSettings.columnOptions.find(opt => opt.value === count)?.spans || []
  
  if (count > oldCount) {
    // 添加列
    for (let i = oldCount; i < count; i++) {
      currentEditingItem.value.columns.push({
        span: spans[i] || 24 / count,
        list: [],
        offset: 0,
        push: 0,
        pull: 0,
        xs: { span: 24 },
        sm: { span: 24 / count },
        md: { span: 24 / count },
        lg: { span: 24 / count },
        xl: { span: 24 / count }
      })
    }
  } else if (count < oldCount) {
    // 删除列
    currentEditingItem.value.columns.splice(count)
  }
  
  // 更新列宽
  currentEditingItem.value.columns.forEach((col, index) => {
    col.span = spans[index] || 24 / count
  })
}

const handleAddGridColumn = () => {
  const count = currentEditingItem.value.columns.length
  if (count < currentEditingItem.value.columnSettings.maxColumns) {
    currentEditingItem.value.columns.push({
      span: Math.floor(24 / (count + 1)),
      list: [],
      offset: 0,
      push: 0,
      pull: 0,
      xs: { span: 24 },
      sm: { span: Math.floor(24 / (count + 1)) },
      md: { span: Math.floor(24 / (count + 1)) },
      lg: { span: Math.floor(24 / (count + 1)) },
      xl: { span: Math.floor(24 / (count + 1)) }
    })
    
    // 重新计算所有列的宽度
    const span = Math.floor(24 / currentEditingItem.value.columns.length)
    currentEditingItem.value.columns.forEach(col => {
      col.span = span
      col.sm.span = span
      col.md.span = span
      col.lg.span = span
      col.xl.span = span
    })
  }
}

const handleRemoveGridColumn = (index) => {
  if (currentEditingItem.value.columns.length > currentEditingItem.value.columnSettings.minColumns) {
    currentEditingItem.value.columns.splice(index, 1)
    
    // 重新计算所有列的宽度
    const span = Math.floor(24 / currentEditingItem.value.columns.length)
    currentEditingItem.value.columns.forEach(col => {
      col.span = span
      col.sm.span = span
      col.md.span = span
      col.lg.span = span
      col.xl.span = span
    })
  }
}

// 子表单相关
const showTableDialog = ref(false)
const previewData = ref([{}])

// 获取列组件
const getColumnComponent = (type) => {
  const componentMap = {
    input: 'el-input',
    textarea: 'el-input',
    number: 'el-input-number',
    date: 'el-date-picker',
    select: 'el-select'
  }
  return componentMap[type] || 'el-input'
}

// 获取列属性
const getColumnProps = (col) => {
  const props = {
    placeholder: `请输入${col.label}`,
    clearable: true
  }
  
  switch (col.type) {
    case 'textarea':
      props.type = 'textarea'
      props.rows = 2
      break
    case 'number':
      props.controls = true
      props.controlsPosition = 'right'
      break
    case 'date':
      props.valueFormat = 'YYYY-MM-DD'
      break
    case 'select':
      props.options = col.options || []
      break
  }
  
  return props
}

// 添加列
const addTableColumn = (tableIndex) => {
  const newColumn = {
    name: `field_${Date.now()}`,
    label: '新字段',
    type: 'input',
    required: false,
    props: {
      placeholder: '请输入',
      clearable: true
    }
  }
  formItems.value[tableIndex].columns.push(newColumn)
}

// 删除列
const removeTableColumn = (tableIndex, columnIndex) => {
  formItems.value[tableIndex].columns.splice(columnIndex, 1)
}

// 添加行
const addRow = () => {
  previewData.value.push({})
}

// 删除行
const removeRow = (index) => {
  previewData.value.splice(index, 1)
}

// 保存子表单
const handleSaveTable = () => {
  showTableDialog.value = false
}

// 处理子表单拖拽
const handleTableDrop = (event, tableIndex) => {
  const data = event.dataTransfer.getData('componentData')
  if (data) {
    try {
      const componentData = JSON.parse(data)
      if (!formItems.value[tableIndex].columns) {
        formItems.value[tableIndex].columns = []
      }
      
      // 添加列配置
      formItems.value[tableIndex].columns.push({
        name: `field_${Date.now()}`,
        label: componentData.label,
        type: componentData.type,
        width: 120,
        required: false,
        props: {
          ...componentData.props,
          placeholder: `请输入${componentData.label}`
        }
      })
    } catch (error) {
      console.error('解析组件数据失败:', error)
    }
  }
}

// 添加列编辑相关
const currentEditingColumn = ref(null)

const handleColumnClick = (column) => {
  currentEditingColumn.value = column
}

const addOption = (column) => {
  if (!column.options) {
    column.options = []
  }
  column.options.push({
    label: '',
    value: ''
  })
}

const removeOption = (column, index) => {
  column.options.splice(index, 1)
}

// 添加计算属性获取面板标题
const getPanelTitle = computed(() => {
  if (!currentEditingItem.value) return '属性设置'
  switch (currentEditingItem.value.type) {
    case 'table':
      return '子表单设置'
    case 'grid':
      return '栅格布局设置'
    default:
      return '字段属性'
  }
})

// 添加列操作方法
const addColumn = () => {
  if (!currentEditingItem.value.columns) {
    currentEditingItem.value.columns = []
  }
  currentEditingItem.value.columns.push({
    label: `列${currentEditingItem.value.columns.length + 1}`,
    type: 'input',
    width: 120,
    required: false,
    props: {
      placeholder: '请输入',
      clearable: true
    },
    options: []
  })
}

// 移动列位置
const moveColumn = (index, direction) => {
  const columns = currentEditingItem.value.columns
  if (direction === 'up' && index > 0) {
    [columns[index], columns[index - 1]] = [columns[index - 1], columns[index]]
  } else if (direction === 'down' && index < columns.length - 1) {
    [columns[index], columns[index + 1]] = [columns[index + 1], columns[index]]
  }
}

// 删除列
const removeColumn = (index) => {
  currentEditingItem.value.columns.splice(index, 1)
}

// 处理行数变化
const handleRowsChange = (value) => {
  currentEditingItem.value.props.defaultRows = value
  // 更新预览数据
  previewData.value = Array(value).fill({})
}

// 添加节点相关方法
const addNodeAfter = (index, type) => {
  const nodeConfig = getNodeConfig(type)
  formItems.value.splice(index + 1, 0, nodeConfig)
}

// 添加子节点相关方法
const addSubNodeAfter = (index, bIndex, sIndex, type) => {
  const nodeConfig = getNodeConfig(type)
  formItems.value[index].columns[bIndex].list.splice(sIndex + 1, 0, nodeConfig)
}

// 添加嵌套节点相关方法
const addNodeAfterNested = (index, bIndex, sIndex, nIndex, nnIndex, type) => {
  const nodeConfig = getNodeConfig(type)
  formItems.value[index].branches[bIndex].nodes[sIndex].branches[nIndex].nodes.splice(nnIndex + 1, 0, nodeConfig)
}

// 获取节点配置
const getNodeConfig = (type) => {
  const configs = {
    approval: {
      type: 'approval',
      name: '审批节点',
      icon: 'User',
      approver: 'manager',
      approvalType: 'or'
    },
    condition: {
      type: 'condition',
      name: '条件分支',
      icon: 'Switch',
      branches: [
        { condition: '', nodes: [] },
        { condition: '其他情况', nodes: [] }
      ]
    },
    parallel: {
      type: 'parallel',
      name: '并行分支',
      icon: 'Share',
      branches: [
        { nodes: [] },
        { nodes: [] }
      ]
    },
    notify: {
      type: 'notify',
      name: '通知节点',
      icon: 'Bell',
      notifyTypes: ['email'],
      notifyContent: ''
    },
    subprocess: {
      type: 'subprocess',
      name: '子流程',
      icon: 'Connection',
      processId: ''
    }
  }
  return configs[type]
}
</script>

<style scoped>
.form-designer {
  display: flex;
  gap: 20px;
  height: calc(100vh - 240px);
  min-height: 600px;
}

.designer-sidebar {
  width: 250px;
  border-right: 1px solid #f0f0f0;
  overflow-y: auto;
}

.designer-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.designer-panel {
  width: 300px;
  border-left: 1px solid #f0f0f0;
  background: #fff;
}

.main-header {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
}

.form-canvas {
  flex: 1;
  padding: 20px;
  background: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  margin: 16px;
  min-height: 400px;
  overflow-y: auto;
}

.form-preview,
.form-json {
  flex: 1;
  padding: 20px;
  background: #fff;
  margin: 16px;
  overflow-y: auto;
}

.component-group {
  margin-bottom: 20px;
}

.group-title {
  padding: 8px 16px;
  color: #999;
  font-size: 14px;
}

.component-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  cursor: move;
  transition: all 0.3s;
  border: 1px solid transparent;
}

.component-item:hover {
  background: #f5f7fa;
  border-color: #1890ff;
}

.form-item {
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.form-item:hover,
.form-item.active {
  border-color: #1890ff;
  background: #f0f7ff;
}

.item-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.item-actions {
  opacity: 0;
  transition: opacity 0.3s;
}

.form-item:hover .item-actions {
  opacity: 1;
}

.panel-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-content {
  padding: 20px;
  overflow-y: auto;
  height: calc(100% - 53px);
}

/* 美化滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #e0e0e0;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 3px;
}

/* 优化组件列表样式 */
.components-list {
  padding: 16px;
  height: 100%;
  overflow-y: auto;
}

.component-group {
  margin-bottom: 20px;
}

.group-title {
  font-size: 14px;
  color: #999;
  margin-bottom: 12px;
  padding-left: 4px;
}

.group-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.component-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;
  background: #fff;
}

.component-item:hover {
  border-color: #1890ff;
  background: #f0f7ff;
  transform: translateY(-2px);
}

.component-item .el-icon {
  font-size: 16px;
  color: #666;
}

.component-item:hover .el-icon {
  color: #1890ff;
}

.column-config {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.column-header span {
  font-weight: 500;
  color: #333;
}

.grid-layout {
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
}

.grid-col {
  min-height: 100px;
  padding: 8px;
  background: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  transition: all 0.3s;
}

.grid-col:hover {
  border-color: #1890ff;
  background: #f0f7ff;
}

.grid-col .el-empty {
  padding: 24px 0;
}

.grid-col .form-item {
  margin-bottom: 8px;
}

.grid-col .form-item:last-child {
  margin-bottom: 0;
}

.form-preview {
  padding: 20px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
  text-align: center;
}

:deep(.el-form-item:last-child .el-form-item__content) {
  justify-content: center;
  margin-left: 0 !important;
}

.table-designer {
  display: flex;
  gap: 20px;
  height: 600px;
}

.designer-sidebar {
  width: 200px;
  border-right: 1px solid #f0f0f0;
  overflow-y: auto;
}

.table-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.columns-container {
  flex: 1;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
  min-height: 200px;
  position: relative;
}

.empty-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  text-align: center;
}

.table-preview {
  width: 400px;
  border-left: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
}

.preview-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: 500;
}

.preview-content {
  flex: 1;
  padding: 16px;
  overflow: auto;
}

.preview-actions {
  margin-top: 16px;
  text-align: center;
}

/* 拖拽相关样式 */
.columns-container.drag-over {
  border: 2px dashed #409eff;
  background: #f0f7ff;
}

/* 组件列表样式 */
.component-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: move;
  transition: all 0.3s;
}

.component-item:hover {
  border-color: #409eff;
  background: #f0f7ff;
}

/* 表格样式优化 */
:deep(.el-table) {
  margin-bottom: 0;
}

:deep(.el-table .el-input) {
  width: 100%;
}

:deep(.el-table .el-tag) {
  margin: 0;
}

/* 美化滚动条 */
.designer-sidebar::-webkit-scrollbar,
.preview-content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.designer-sidebar::-webkit-scrollbar-thumb,
.preview-content::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background: #e0e0e0;
}

.designer-sidebar::-webkit-scrollbar-track,
.preview-content::-webkit-scrollbar-track {
  border-radius: 3px;
  background: #f5f5f5;
}

.column-cell {
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.column-cell:hover {
  background: #f5f7fa;
}

.column-cell.active {
  background: #e6f7ff;
  color: #1890ff;
}

.table-panel {
  width: 300px;
  border-left: 1px solid #f0f0f0;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.options-editor {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.option-item .el-input {
  flex: 1;
}

/* 美化滚动条 */
.panel-content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.panel-content::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background: #e0e0e0;
}

.panel-content::-webkit-scrollbar-track {
  border-radius: 3px;
  background: #f5f5f5;
}

.table-form {
  width: 100%;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #f0f0f0;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.table-content {
  padding: 16px;
  min-height: 120px;
  position: relative;
}

.empty-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  text-align: center;
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-table) {
  margin-bottom: 0;
}

:deep(.el-table .el-input.is-disabled .el-input__wrapper) {
  background: #f5f7fa;
}

:deep(.el-table td) {
  padding: 8px;
}

/* 拖拽相关样式 */
.table-content.drag-over {
  background: #f0f7ff;
  border: 2px dashed #1890ff;
}
</style> 